// ui/power_switch.go
package ui

import (
	"device_manager/api"
	"device_manager/config"
	"device_manager/utils"
	"fmt"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"gorm.io/gorm"
)

func CreatePowerSwitchTab(db *gorm.DB, cfg *config.Config) fyne.CanvasObject {
	devices := loadDevices(db, "电源空开")

	deviceList := widget.NewList(
		func() int { return len(devices) },
		func() fyne.CanvasObject {
			nameLabel := widget.NewLabel("")
			snLabel := widget.NewLabel("")
			onButton := widget.NewButton("开电", nil)
			offButton := widget.NewButton("关电", nil)
			queryButton := widget.NewButton("查询用电", nil)
			logButton := widget.NewButton("查看日志", nil)
			row := container.NewHBox(
				nameLabel,
				snLabel,
				onButton,
				offButton,
				queryButton,
				logButton,
			)
			return row
		},
		func(i widget.ListItemID, o fyne.CanvasObject) {
			row := o.(*fyne.Container)
			labels := row.Objects

			nameLabel := labels[0].(*widget.Label)
			snLabel := labels[1].(*widget.Label)
			onButton := labels[2].(*widget.Button)
			offButton := labels[3].(*widget.Button)
			queryButton := labels[4].(*widget.Button)
			logButton := labels[5].(*widget.Button)

			device := devices[i]
			nameLabel.SetText(device.Name)
			snLabel.SetText(device.DeviceSN)

			onButton.OnTapped = func() {
				err := api.TurnOnPower(&device, cfg)
				result := "成功"
				if err != nil {
					result = "失败：" + err.Error()
					utils.ShowError(err)
				} else {
					utils.ShowInfo("开电指令已发送")
				}
				logAction(db, device.ID, "开电", result)
			}

			offButton.OnTapped = func() {
				err := api.TurnOffPower(&device, cfg)
				result := "成功"
				if err != nil {
					result = "失败：" + err.Error()
					utils.ShowError(err)
				} else {
					utils.ShowInfo("关电指令已发送")
				}
				logAction(db, device.ID, "关电", result)
			}

			queryButton.OnTapped = func() {
				info, err := api.GetPowerInfo(&device, cfg)
				result := "成功"
				if err != nil {
					result = "失败：" + err.Error()
					utils.ShowError(err)
				} else {
					utils.ShowInfo(fmt.Sprintf("用电情况：%v", info))
				}
				logAction(db, device.ID, "查询用电情况", result)
			}

			logButton.OnTapped = func() {
				showDeviceLogs(db, &device)
			}
		},
	)

	addButton := widget.NewButton("刷新列表", func() {
		devices = loadDevices(db, "电源空开")
		deviceList.Refresh()
	})

	header := container.NewHBox(
		widget.NewLabelWithStyle("设备名称", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}),
		widget.NewLabelWithStyle("设备SN", fyne.TextAlignLeading, fyne.TextStyle{Bold: true}),
		widget.NewLabel(""),
		widget.NewLabel(""),
		widget.NewLabel(""),
		widget.NewLabel(""),
	)

	content := container.NewBorder(
		header,
		addButton,
		nil,
		nil,
		deviceList,
	)

	return content
}
